import React, { useEffect, useState } from 'react';
import _ from 'lodash';
import { DatePicker } from 'antd';
import moment from 'moment';
import PropTypes from 'prop-types';

import { getServerTime } from '@api/system';
import './index.less';

function range(start, end) {
  const result = [];
  for (let i = start; i < end; i++) {
    result.push(i);
  }
  return result;
}
const timeFormat = 'YYYY-MM-DD HH:mm';

const TaskLimitDate = ({ onDateStartChange, onDateEndChange }) => {
  const nowDate = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
  const [serverDate, setServerDate] = useState(nowDate);
  const [disabled, setDisabled] = useState(false);
  const [shouldDisableTime, setShouldDisableTime] = useState(false);
  const [startDate, setStartDate] = useState();
  const [endDate, setEndDate] = useState();

  useEffect(() => {
    getServerTime().then(res => {
      const time = _.get(res, 'data.data.timestamp');
      setServerDate(time);
      setDisabled(false);
    });
  }, []);

  const serverTime = moment(serverDate).format(timeFormat);

  const disabledDate = (current, disabledTime) => {
    const disabledMoment = moment(disabledTime);
    return current && current < disabledMoment.startOf('day');
  };

  const onStartDateChange = time => {
    const suspectEndTime = moment(time).add(30, 'minute');
    const newEndTime = moment.max(endDate, suspectEndTime);
    setStartDate(time);
    onDateStartChange(time);
    if (new Date(newEndTime).toString() === 'Invalid Date') {
      setEndDate();
      onDateEndChange();
      return;
    }
    setEndDate(newEndTime);
    onDateEndChange(newEndTime);
  };

  const onEndDateChange = time => {
    const shouldDisable = time > moment(startDate).endOf('day');

    setShouldDisableTime(shouldDisable);
    setEndDate(time);
    onDateEndChange(time);
  };

  const disabledDateTime = (disabledTime, featMinute, DataType) => {
    let disTime = moment(disabledTime);
    if (featMinute) {
      disTime = disTime.add(featMinute, 'minutes');
    }
    const hour = disTime.hour();
    const minutes = disTime.minute();
    const NowHour = {
      start: startDate ? startDate.hour() : null,
      end: endDate ? endDate.hour() : null
    }[DataType];
    let disableFlage = NowHour > hour ? true : false;
    return {
      disabledHours: () => range(0, 24).splice(0, hour),
      disabledMinutes: () => (!disableFlage ? range(0, 60).splice(0, minutes) : range(0, 0))
    };
  };

  return (
    <div className="date-picker-range">
      <DatePicker
        className="daily-start"
        placeholder="开始时间"
        disabledDate={current => disabledDate(current, serverDate)}
        disabledTime={() => disabledDateTime(serverDate, null, 'start')}
        renderExtraFooter={() => (
          <div className={'date-limit-picker'}>服务器时间：{serverTime}</div>
        )}
        value={startDate}
        showTime={{ format: 'HH:mm' }}
        disabled={disabled}
        format={timeFormat}
        onChange={onStartDateChange}
        getCalendarContainer={triggerNode => triggerNode.parentNode}
      />
      &nbsp;&nbsp;
      <DatePicker
        className="daily-end"
        placeholder="结束时间"
        disabledDate={current => disabledDate(current, startDate)}
        disabledTime={
          shouldDisableTime ? null : () => disabledDateTime(startDate || serverDate, 30, 'end')
        }
        renderExtraFooter={() => (
          <div className={'date-limit-picker'}>服务器时间：{serverTime}</div>
        )}
        value={endDate}
        showTime={{ format: 'HH:mm' }}
        disabled={disabled}
        format={timeFormat}
        onChange={onEndDateChange}
        getCalendarContainer={triggerNode => triggerNode.parentNode}
      />
    </div>
  );
};

TaskLimitDate.propTypes = {
  onDateStartChange: PropTypes.func.isRequired,
  onDateEndChange: PropTypes.func.isRequired
};

export default TaskLimitDate;
